import $ from "@jquery";
/**
 * 返回Body子元素级被选中的元素集合
 */
export function getSelectionElements(doc = document) {
  const selection = doc.getSelection();
  if (selection.rangeCount === 0) return [];

  const range = selection.getRangeAt(0);
  let start = $(range.startContainer);
  let end = $(range.endContainer);
  let commonAncestor = $(range.commonAncestorContainer);

  let selectionElements = [commonAncestor];

  if (!commonAncestor.is("body")) {
    return selectionElements;
  }

  if (!start.is(end) && !start.is("body") && !end.is("body")) {
    //跨body级元素选择
    start = start.parentOfBodyChild();
    end = end.parentOfBodyChild();
    selectionElements = [start, ...start.nextUntil(end), end];
  } else if (!start.is("body") && end.is("body")) {
    //处理双击选中文本时start or end 中的某一个变成body现象
    selectionElements = [start];
  } else if (!end.is(body) && start.is("body")) {
    //处理双击选中文本时start or end 中的某一个变成body现象
    selectionElements = [end];
  }
  return selectionElements;
}
